<?php

class UsersController extends GxController {
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('sendMailtouserpromotion', 'trainerProfile', 'setUserSession', 'subscribe', 'runningclasses', 'previousclasses'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('learnUser'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionTrainerProfile($authKey) {
        $this->layout = 'detailspage';
        $classTrainerRate = '';
        $classCoursename = '';
        $classtotalCountTrainerate = '';
        $action = '';
        $loginUserId = getLoginUserId();
        $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
        $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
        if (!empty($classes) || !empty($courses)) {
            if (!empty($classes)) {
                $profiles = getUserTypeByClassCourse('Classes', $classes->id);
                $userType = getUserType('Classes', $classes->id);
                $classesCourse = $classes;
                $classtype = 'class';
                $imagePath = getImagePathByClassCourse('Classes', $classes->id);
                $classTrainerRate = Classes::trainerPossitiverate($userType, $classes);
                $classtotalCountTrainerate = Classes::trainertotalRate($userType, $classes);
                $classCoursename = $classes->class_titile;
                $action = 'classes/viewClass';
            }
            if (!empty($courses)) {
                $classtype = 'course';
                $classesCourse = $courses;
                $profiles = getUserTypeByClassCourse('Courses', $courses->id);
                $userType = getUserType('Courses', $courses->id);
                $imagePath = getImagePathByClassCourse('Courses', $courses->id);
                $classTrainerRate = Classes::trainerPossitiverate($userType, $courses);
                $classtotalCountTrainerate = Classes::trainertotalRate($userType, $courses);
                $classCoursename = $courses->course_titile;
                $action = 'Courses/viewCourse';
            }
            $trainerType = ($userType != 'backend') ? 'trainer_front_end_user_id' : 'trainer_backend_user_id';
            $trainerFolow = count(TrainerFollow::model()->findByAttributes(array('folower_user_id' => $loginUserId, $trainerType => $profiles->user_id)));
            $folowers = ($trainerFolow > 0) ? Message::FOLOWER_ON_SKILLHIPPO : Message::FOLOW_ON_SKILLHIPPO;
            $this->render('trainerProfile', array('classtype' => $classtype, 'profiles' => $profiles, 'classes' => $classesCourse, 'imagePath' => $imagePath, 'userType' => $userType,
                'action' => $action, 'classCoursename' => $classCoursename, 'classTrainerRate' => $classTrainerRate, 'classtotalCountTrainerate' => $classtotalCountTrainerate,
                'authKey' => $authKey, 'folowers' => $folowers));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionlearnUser() {
        $this->layout = 'detailspage';
        $purchaseClassCourse = new CActiveDataProvider('PurchaseOrder', array(
                    'criteria' => array(
                        'condition' => 'users_id=' . getLoginUserId(),
                        'order' => 'id DESC',
                    ),
                ));
        $dataProvider = new CActiveDataProvider('MakeQuery', array(
                    'criteria' => array(
                        'condition' => 'users_id=' . getLoginUserId(),
                        'order' => 'id DESC',
                    ),
                ));

        $this->render('learn', array('dataProvider' => $dataProvider, 'purchaseClassCourse' => $purchaseClassCourse));
    }

    public function actionsubscribe() {
        $model = new Users;
        if (!empty($_POST['Users'])) {
            $model->setScenario('updateSubscription'); // 
            $model->setAttributes($_POST['Users']);
            $model->setAttribute('password', 'subscribe');
            $model->setAttribute('confirm_password', 'subscribe');
            if ($model->validate()) {
                $userDetail = $model->findByAttributes(array('username' => $model->username));
                if (isset($userDetail->id)) {
                    /* User already exist */
                    if ($userDetail->id <> "" && $userDetail->issubscribe == SkillConfig::STATUS_ACTIVE) {
                        echo CJSON::encode(array(
                            'status' => 'already_subscribe'
                        ));
                        Yii::app()->end();
                    } else {
                        $model->updateByPk($userDetail->id, array('issubscribe' => SkillConfig::STATUS_ACTIVE));
                        echo CJSON::encode(array(
                            'status' => 'success'
                        ));
                        Yii::app()->end();
                    }
                } else {
                    $model->setAttribute('status', SkillConfig::STATUS_DEACTIVE);
                    $model->setAttribute('issubscribe', SkillConfig::STATUS_ACTIVE);
                    $model->save();
                    $mailmodel = EmailTemplate::model()->findByPk(Message::NEWS_LETTER);
                    $userText = $mailmodel->body;
                    $mailbody = array('value' => $userText, 'type' => 'raw');
                    $subject = $mailmodel->subject;
                    $userName = $model->username;
                    $mailto = $model->username;
                    $arrayFind = array('[username]');
                    $arrayReplace = array($userName);
                    $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                    $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                    $subject = $mailmodel->subject;
                    $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                    try {
                        SkillSendMail::SendMail($mailto, $subject, $body);
                        Promotion::promotioncoupon(Message::DISCOUNT_COUPON_NEWSLETTER, $mailto);
                        echo CJSON::encode(array(
                            'status' => 'success'
                        ));

                        Yii::app()->end();
                    } catch (Exception $e) {
                        $result = $e;
                        exit;
                    }
                }
            } else {
                $error = CActiveForm::validate($model);
                if ($error != '[]')
                    echo $error;
                Yii::app()->end();
            }
        }
    }

    public function actionrunningclasses($authKey) {
        $this->layout = 'detailspage';
        $allClassCourseInfo = array();
        $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
        $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
        if (!empty($classes) || !empty($courses)) {
            if (!empty($classes)) {
                $profiles = getUserTypeByClassCourse('Classes', $classes->id);
                $userType = getUserType('Classes', $classes->id);
            }
            if (!empty($courses)) {
                $profiles = getUserTypeByClassCourse('Courses', $courses->id);
                $userType = getUserType('Courses', $courses->id);
            }
            if (isset($_GET['type']) && $_GET['type'] == 'course') {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $allClassCourseInfo = runningCurrentCoursesByUser($profiles, $userType, $_GET);
                } else {
                    $allClassCourseInfo = runningCurrentCoursesByUser($profiles, $userType, $_GET);
                    usort($allClassCourseInfo, 'date_compare');
                }
            } elseif (isset($_GET['type']) && ($_GET['type'] == 'workshop' OR $_GET['type'] == 'curatedclasses')) {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $allClassCourseInfo = literalEndingTommorow($profiles, $userType, $_GET);
                    $comapreFunction = ($_GET['priceorder'] == '1' ? 'price_compare_ascending' : ($_GET['priceorder'] == '2' ? 'price_compare_descending' : ($_GET['mostpopular'] == '1' ? 'hitcounter_compare_descending' : 'hitcounter_compare_ascending')));
                    usort($allClassCourseInfo, $comapreFunction);
                } else {
                    $allClassCourseInfo = literalEndingTommorow($profiles, $userType, $_GET);
                }
            } else {
                if (isset($_GET['priceorder']) OR isset($_GET['mostpopular'])) {
                    $classDetails = literalEndingTommorow($profiles, $userType, $_GET);
                    $courseDetails = runningCurrentCoursesByUser($profiles, $userType, $_GET); //Null parameter means these value $profiles, $userType, $getValue)
                    $allClassCourseInfo = array_merge($classDetails, $courseDetails);
                    $comapreFunction = ($_GET['priceorder'] == '1' ? 'price_compare_ascending' : ($_GET['priceorder'] == '2' ? 'price_compare_descending' : ($_GET['mostpopular'] == '1' ? 'hitcounter_compare_descending' : 'hitcounter_compare_ascending')));
                    usort($allClassCourseInfo, $comapreFunction);
                } else {
                    $classDetails = literalEndingTommorow($profiles, $userType, $_GET);
                    $courseDetails = runningCurrentCoursesByUser($profiles, $userType, $_GET); //Null parameter means these value $profiles, $userType, $getValue)
                    $allClassCourseInfo = array_merge($classDetails, $courseDetails);
                    usort($allClassCourseInfo, 'date_compare');
                }
            }
            $dataProvider = new CArrayDataProvider($allClassCourseInfo, array(
                        'sort' => array(
                            'attributes' => array(
                                'start_date',
                            ),
                        ),
                        'pagination' => array(
                            'pageSize' => 20,
                        ),
                    ));

            $this->render('_runningClasses', array('dataProvider' => $dataProvider, 'profiles' => $profiles, 'userType' => $userType,
                'authKey' => $authKey));
        }

        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionpreviousclasses($authKey) {
        $this->layout = 'detailspage';
        $classes = Classes::model()->findByAttributes(array('auth_key' => $authKey));
        $courses = Courses::model()->findByAttributes(array('auth_key' => $authKey));
        if (!empty($classes) || !empty($courses)) {
            if (!empty($classes)) {
                $profiles = getUserTypeByClassCourse('Classes', $classes->id);
                $userType = getUserType('Classes', $classes->id);
            }
            if (!empty($courses)) {
                $profiles = getUserTypeByClassCourse('Courses', $courses->id);
                $userType = getUserType('Courses', $courses->id);
            }
            $coursesArray = previousClassCourseByuser($profiles, $userType);
            $dataProvider = new CArrayDataProvider($coursesArray, array(
                        'sort' => array(
                            'attributes' => array(
                                'start_date',
                            ),
                        ),
                        'pagination' => array(
                            'pageSize' => 20,
                        ),
                    ));

            $this->render('_previusClasses', array('dataProvider' => $dataProvider, 'profiles' => $profiles,
                'authKey' => $authKey));
        }
        else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionsetUserSession() {
        if ($_POST['sessionVal'] != '2') {
            Yii::app()->user->setState('trainer', SkillConfig::USER_TRAINER);
        }
        if ($_POST['sessionVal'] != '1') {
            Yii::app()->user->setState('trainer', SkillConfig::WEB_USER);
        }
    }

    public function actionsendMailtouserpromotion($couponName, $username) {
        $mailmodel = EmailTemplate::model()->findByPk(Message::COUPON_SEND_TO_USER);
        $userText = $mailmodel->body;
        $mailbody = array('value' => $userText, 'type' => 'raw');
        $mailto = $username;
        $arrayFind = array('[username]', '[coupon_code]');
        $arrayReplace = array($username, $couponName);
        $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
        $mailtemp = Template::model()->findByPk($mailmodel->template_id);
        $subject = $mailmodel->subject;
        $body = $this->renderPartial('frontend.www.themes.front-end.views.mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
        try {
            SkillSendMail::SendMail($mailto, $subject, $body);
        } catch (Exception $e) {
            $result = $e;
            exit;
        }
    }

}
